package com.example.demo.service;

import antlr.StringUtils;
import com.example.demo.po.Label;
import com.example.demo.po.Users;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public void save(Users users) {
        userRepository.save(users);
    }

    public Users findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public List<Users> get_by_username(String username) {
        return userRepository.get_by_username(username);
    }

    public List<Map> getAllUser() {
        return userRepository.getAllUser();
    }

    public Integer update_user(Integer id, String username) {
        return userRepository.update_user(id,username);
    }

    public void delete(Users users) {
        userRepository.delete(users);
    }

    //这里我的前端给我传的是参数是一个map
    private Specification<Users> createSpecification(String username) {

        //匿名内部类,实现接口方法
        Specification<Users> spec = new Specification() {

            @Override
            public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {

                //创建集合,用于存放拼接的条件
                List<Predicate> list = new ArrayList<>();

                if(!username.isEmpty()){
                    String s = username;
                    list.add(cb.like(root.get("username"),s));
                }

                return cb.and(list.toArray(new Predicate[list.size()]));
            }
        };
        return spec;
    }


    //多条件加分页查询
    public Page<Users> findUsername(String username,int page,int size){
        Specification<Users> spec = createSpecification(username);
        Pageable pageable = PageRequest.of(page - 1, size);
        return userRepository.findAll(spec,pageable);
    }




}
